package com.justyh.ssm.util;

import jxl.Workbook;
import jxl.format.*;
import jxl.write.*;
import jxl.write.Pattern;
import org.apache.commons.logging.Log;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.*;

/**
 * Created by Chejianer on 2016/9/2.
 */
public class ExcelUtil {
    private final static SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    public static void excelOut(String fileName, Object[] columArr,Object[] filedNameArr,
                                List<? extends Object> listContent, HttpServletResponse response){
        WritableWorkbook book=null;
        OutputStream os=null;
        String result="系统提示：Excel文件导出成功！";
        try {
            //获取输出流
            os=response.getOutputStream();
            //清空输出流
            response.reset();
            //设定输出文件头
            response.setHeader("Content-disposition","attachment;filename="+new String(fileName.getBytes("GB2312"),"8859_1")+".xls");
            //定义输出类型
            response.setContentType("application/msexcel");
            //建立excel文件
            book= Workbook.createWorkbook(os);
            //创建一个工作表
            WritableSheet sheet=book.createSheet("sheet",0);
            //给sheet电子版中所有的列设置默认的列的宽度;
            sheet.getSettings().setDefaultColumnWidth(20);
            //先把标题写好
            //String[] headers={"学号","姓名","性别"};
            //Object[] columArr=exportMap.keySet().toArray();
            outExcelHeaders(columArr,sheet);
           // Object[] filedNameArr=exportMap.values().toArray();
            //以下为Excel正文数据
            /*for(int i=0;i<arrayList.size();i++){
                //获取类对象
                Object ob=arrayList.get(i);
                Class cl=ob.getClass();
                Field[] f=cl.getDeclaredFields();
                for(int j=0;j<f.length;j++){
                    //获得读写权限
                    f[j].setAccessible(true);
                    Label label=new Label(j,i+1,String.valueOf(f[j].get(ob)));
                    sheet.addCell(label);
                }
            }*/

            int i=1;
            for(Object obj:listContent){
                int j = 0;
                String fieldNameTemp = null;
                Object value = null;
                Method method=null;
                Class methodTypeClass=null;
                //sheet.addCell(new Label(j, i, String.valueOf(i)));
                //j++;
                for (Object fieldName : filedNameArr) {
                    fieldNameTemp = "get" + fieldName.toString().substring(0, 1).toUpperCase()
                            + fieldName.toString().substring(1);
                    method = obj.getClass().getMethod(fieldNameTemp, null);
                    methodTypeClass = method.getReturnType();
                    //时间格式转换
                    if (Date.class.getSimpleName().equals(methodTypeClass.getSimpleName())) {
                        value = dateFormat.format((Date)method.invoke(obj, null));
                    }else{
                        value = method.invoke(obj, null);
                    }
                    if (value == null) {
                        value = "";
                    }
                    sheet.addCell(new Label(j, i, value.toString()));
                    j++;
                }
                i++;
            }

            //写入
            book.write();
            book.close();
        } catch (Exception e) {
            result="系统提示：Excel文件导出失败！";
            e.printStackTrace();
        }
    }


    /**
     * 设置表头信息，利用jxl
     * @param headersInfo 表头信息数组
     * @param sheet 表
     * @throws WriteException
     */
    public static void outExcelHeaders(Object[] headersInfo,WritableSheet sheet) throws WriteException {
        //设置字体样式
        WritableFont font=new WritableFont(WritableFont.ARIAL,14,WritableFont.BOLD,false, UnderlineStyle.NO_UNDERLINE);
        WritableCellFormat cellFormat=new WritableCellFormat(font);
        cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
        for(int i=0;i<headersInfo.length;i++){
            Label label=new Label(i,0,headersInfo[i].toString(),cellFormat);
            sheet.addCell(label);

        }
    }
}
